from urllib.parse import uses_netloc

from flask import Flask, render_template, request, send_from_directory, redirect, url_for, abort
import os
from flask import session
from flask_wtf import CSRFProtect

# from . import updown_bp


app = Flask(__name__)

# app.register_blueprint(updown_bp)
app.secret_key = os.urandom(24)

# csrf = CSRFProtect(app)

# 上传文件存储路径
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.template_folder = 'templates'
app.static_folder = 'static'


@app.route('/')
def index():
    if not session:
        return redirect(url_for('login'))
    # 确保上传文件夹存在
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    # 获取上传文件夹中的文件列表
    files = os.listdir(app.config['UPLOAD_FOLDER'])
    return render_template('up_down.html', files=files)

@app.route('/login', methods=['GET', 'POST'])
# @app.route('/')
def login():
    if request.method == 'POST':
    #     return render_template('login.html')
    # if not session.get('username', None):
    #     return render_template('login.html')

    # else:
        username = request.form.get('username')
        password = request.form.get('password')
        if username != 'alicat' or password != '123456':
            return '用户名或密码错误', 400
        else:
            session.permanent = True
            session['username'] = username
            return redirect(url_for('index'))
    return render_template('login.html')


@app.route('/upload', methods=["POST"])
def upload_file():
    if 'file' not in request.files:
        return 'No file part', 400
    # 判断下是否有输入文件
    file = request.files['file']
    if file.filename == '':
        return '请选择上传文件', 400

    # 保存文件到指定路径
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
    # 更新网页，显示 index 页面
    return redirect(url_for('index'))

@app.route('/download/<filename>')
def download_file(filename):
    # 从上传文件夹中发送文件（下载）
    return send_from_directory(os.path.join(os.getcwd(), app.config['UPLOAD_FOLDER']), filename, as_attachment=True)


@app.route('/delete/<filename>', methods=['DELETE', "POST"])
def delete_file(filename):
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    if os.path.exists(file_path):
        os.remove(file_path)
        return redirect(url_for('index', filename=filename))
    else:
        abort(404, description="File not found")


if __name__ == '__main__':
    # 以debug模式运行，只有当前电脑能访问此网页，其他电脑不行
    app.run(debug=True)








